<template>
  <div>
    <h1 @click="openNewPage">中控数据看板</h1>
    <vxe-table
        resizable
        border
        show-overflow
        show-header-overflow
        show-footer-overflow
        ref="xTable"
        class="mytable-scrollbar"
        v-loading="loading"
        :height="tableHeight"
        :sort-config="{trigger: 'cell'}"
        :expand-config="{accordion: true, lazy: true, loadMethod: loadContentMethod}"
        :scroll-x="{enabled: true, gt: 10}"
        :scroll-y="{enabled: true, gt: 100}">
      <vxe-column type="expand" width="80" align="center">
        <template #content="{ row }">
          <vxe-grid :columns="row.childCols" :data="row.childData"/>
        </template>
      </vxe-column>
      <vxe-column type="seq" title="序号" show-header-overflow="title" />
      <vxe-column field="machinename" title="机台" align="left" sortable show-header-overflow="title" />
      <vxe-column field="tubes" title="管数" align="center" sortable show-header-overflow="title" />
      <vxe-column field="count_machinename" title="明细条数" align="center" sortable show-header-overflow="title" />
      <vxe-column field="inechart" title="折线图" show-header-overflow="title"  >
        <template #default="{ row }">
          <vxe-button @click="buttonClick(row)">折线图</vxe-button>
        </template>
      </vxe-column>
    </vxe-table>
  </div>
</template>

<script>
import {getSupconDatasH,getSupconDatasHD} from '@/services/DataService'

export default {
  name: 'MyComponent',
  data () {
    return {
      loading: true,
      days: 100,//默认100
      tableHeight: 0 // 响应式属性，用于存储表格高度
    }
  },
  async mounted () {
    document.title = '中控数据看板明细';
    this.setWindowHeight(); // 设置初始高度
    window.addEventListener('resize', this.setWindowHeight); // 监听窗口大小变化
    // 调用一个异步函数来获取数据大小
    this.fetchDataAndLoadTable();
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setWindowHeight); // 组件销毁前移除监听器
  },
  methods: {
    openNewPage() {
      const url_href = window.location.href;
      const baseUrl = url_href.split('#/')[0];
      // 在新标签页中打开
      let url = `${baseUrl}#/machinepie`;
      console.log(url)
      window.open(url, '_blank'); // 在新标签页中打开
    },
    async loadContentMethod ({ row }) {
      const res2 = await getSupconDatasHD(this.days,row.machinename);
      return new Promise(resolve => {
        setTimeout(() => {
          const childCols = [
            { type: 'seq', title: '明细序号' },
            { field: 'machinename', title: '机台',align: "center" },
            { field: 'tubes', title: '管数', align: 'center' },
            { field: 'batchname', title: '缸号', align: 'center' },
            { field: 'rundate', title: '运行当天的日期', align: 'center' },
            { field: 't_rank', title: '运行当天第几缸', align: 'center' },
            { field: 'dyeprogname', title: '明细缸号', align: 'center' },
            { field: 'starttime', title: '开始时间', align: 'center' },
            { field: 'endtime', title: '结束时间', align: 'center' },
            { field: 'runtime', title: '运行时间', align: 'center' }
          ]
          const childData = []

          const size = res2.length;
          for (let index = 0; index < size; index++) {
            const starttimeStr = res2[index].starttime;
            const endtimeStr = res2[index].endtime;
            const timeDifference = this.calculateTimeDifference(starttimeStr,endtimeStr);
            let runtime = "";
            if(timeDifference.days>0){
              runtime = runtime+timeDifference.days+"天"
            }
            if(timeDifference.hours>0){
              runtime = runtime+timeDifference.hours+"小时"
            }
            if(timeDifference.minutes>0){
              runtime = runtime+timeDifference.minutes+"分钟"
            }
            childData.push({
              machinename: res2[index].machinename,
              batchname: res2[index].batchname,
              tubes: res2[index].tubes,
              t_rank: "第"+res2[index].t_rank+"缸",
              rundate: res2[index].rundate,
              dyeprogname: res2[index].dyeprogname,
              starttime: res2[index].starttime,
              endtime: res2[index].endtime,
              runtime: runtime,
            });
          }
          row.childCols = childCols
          row.childData = childData
          resolve()
        }, 200)
      })
    },
    async fetchDataAndLoadTable() {
      try {
        const res = await getSupconDatasH(this.days);
        // 等待 DOM 更新后再加载数据
        this.$nextTick(() => {
          const $table = this.$refs.xTable;

          this.mockList(res).then(data => {
            if ($table) {
              $table.loadData(data);
            }
          });
        });

        this.loading = false;
      } catch (error) {
        this.loading = false;
        console.error('Error fetching data:', error);
        // 错误处理...
      }
    },
    mockList (res) {
      const size = res.length;
      return new Promise(resolve => {
        const list = []
        for (let index = 0; index < size; index++) {
          list.push({
            machinename: res[index].machinename,
            tubes: res[index].tubes,
            count_machinename: res[index].count_machinename,
            childCols: [], childData: []
          })
        }
        resolve(list)
      })
    },
    async buttonClick(row) {
      let machinename = row.machinename;
      machinename = encodeURIComponent(machinename);
      const url_href = window.location.href;
      const baseUrl = url_href.split('#/')[0];
      // 在新标签页中打开
      let url = `${baseUrl}#/machineline?machinename=${machinename}&days=${5}`;
      console.log(url)
      window.open(url, '_blank'); // 在新标签页中打开
    },
    setWindowHeight() {
      // 计算可用高度，这里只是一个示例，你可能需要根据你的布局进行调整
      const windowHeight = window.innerHeight;
      // 假设你要留给表格之外的内容（如页眉、页脚等）100px的高度
      this.tableHeight = windowHeight - 90;
    },
    calculateTimeDifference(startTimeStr, endTimeStr) {
      // 创建Date对象
      const startTime = new Date(startTimeStr);
      const endTime = new Date(endTimeStr);

      // 确保date2是较大的日期
      const diff = endTime - startTime;

      // 如果日期字符串格式不正确或date2小于date1，则返回NaN
      if (isNaN(diff)) {
        return { days: NaN, hours: NaN, minutes: NaN };
      }

      // 计算天数差
      const daysDiff = Math.floor(diff / (1000 * 60 * 60 * 24));

      // 计算剩余的小时差
      const hoursDiff = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));

      // 计算剩余的分钟差
      const minutesDiff = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));

      // 返回结果对象
      return { days: daysDiff, hours: hoursDiff, minutes: minutesDiff };
    },
  }
}
</script>

<style scoped>
.vxe-button {
  /* 按钮的默认样式 */
  padding: 5px 10px;
  background-color: #02D1FFFF;
  color: #fff;
  border: none;
  cursor: pointer;
}


/*滚动条整体部分*/
.mytable-scrollbar ::-webkit-scrollbar {
  width: 10px;
  height: 10px;
}
/*滚动条的轨道*/
.mytable-scrollbar ::-webkit-scrollbar-track {
  background-color: #FFFFFF;
}
/*滚动条里面的小方块，能向上向下移动*/
.mytable-scrollbar ::-webkit-scrollbar-thumb {
  background-color: #bfbfbf;
  border-radius: 5px;
  border: 1px solid #F1F1F1;
  box-shadow: inset 0 0 6px rgba(0,0,0,.3);
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:hover {
  background-color: #A8A8A8;
}
.mytable-scrollbar ::-webkit-scrollbar-thumb:active {
  background-color: #787878;
}
/*边角，即两个滚动条的交汇处*/
.mytable-scrollbar ::-webkit-scrollbar-corner {
  background-color: #FFFFFF;
}
</style>
